package com.xgr.wonderful.adapter;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.xgr.wonderful.MyApplication;
import com.xgr.wonderful.R;
import com.xgr.wonderful.activity.GalleryActivity;
import com.xgr.wonderful.activity.PersonalCenterActivity;
import com.xgr.wonderful.activity.PersonalCenterActivity2;
import com.xgr.wonderful.constant.Constant;
import com.xgr.wonderful.entity.Comment;
import com.xgr.wonderful.entity.Photo;
import com.xgr.wonderful.entity.Status;
import com.xgr.wonderful.sns.SharePopWindow;
import com.xgr.wonderful.utils.DisplayUtils;
import com.xgr.wonderful.utils.HttpProxy;
import com.xgr.wonderful.utils.HttpProxy.IHttpRequestListener;
import com.xgr.wonderful.utils.LocalLikeRelationsUtils;
import com.xgr.wonderful.utils.LocalUserUtils;
import com.xgr.wonderful.utils.LogUtils;
import com.xgr.wonderful.utils.ToastFactory;
import com.xgr.wonderful.view.CircleImageView;


/**
 * @author lsj
 *
 */
public class CommentAdapter  extends BaseContentAdapter<Comment>{
	
	private String TAG ="CommentAdapter" ;
	
	private Status status ; //要评论的状态 
	private Activity activity ;
	
	private final int TYPE_COUNT = 2;
	private final int FIRST_TYPE =0;
	private final int OTHER_TYPE =1 ;
	
	private int currentType ;
	
	private HttpProxy httpProxy ;
	
	private Animation scaleAnimation;
	
	public CommentAdapter(Context context, List<Comment> list, Status status) {
		super(context, list);
		this.status = status;
		this.activity = (Activity)context; 
		httpProxy = new HttpProxy() ;
		scaleAnimation= AnimationUtils.loadAnimation(context, R.anim.scale_anim) ;
	}
	
	@Override
	public int getCount() {
		//注意
		if (status!= null){
			if (dataList!=null && dataList.size()!= 0){
				LogUtils.i(TAG, "getCount:"+ (dataList.size()+1)) ;
				return dataList.size()+1;
			}else {
				return 1;
			}
		}
		return 0;
	}
	

	@Override
	public Comment getItem(int position) {
		//注意
		if (position != 0){
			if (dataList!= null && dataList.size()!=0){
				return dataList.get(position-1) ;
			}else {
				return null ;
			}	
		}else {
			return null ;
		}
	}
	
	@Override
	public int getViewTypeCount() {
		return TYPE_COUNT;
	}
	
	@Override
	public int getItemViewType(int position) {
		if (position == 0) {
			return FIRST_TYPE;// 第一种视图
		} else {
			return OTHER_TYPE;
		}
	}
	

	@Override
	public View getConvertView(int position, View convertView, ViewGroup parent) {
		View statusView = null ;
		View commentView = null ;
		currentType = getItemViewType(position) ;
		LogUtils.i(TAG, "position:"+position) ;
		switch (currentType) {
		case FIRST_TYPE:
			statusView = convertView ;
			StatusHolder statusHolder  = null ;
			if (statusView == null){
				statusView = mInflater.inflate(
						R.layout.item_status_homepage1, null);
				statusHolder = new StatusHolder();
				statusHolder.mAvatar = (CircleImageView)statusView.
						findViewById(R.id.item_homepage_userphoto) ;
				statusHolder.mUsername = (TextView)statusView.
						findViewById(R.id.item_homepage_username);
				statusHolder.mDistance= (TextView)statusView.
						findViewById(R.id.item_homepage_distance);
				statusHolder.mTime = (TextView)statusView.
						findViewById(R.id.item_homepage_time);
				
				statusHolder.mImage = (ImageView)statusView.
						findViewById(R.id.item_homepage_image);
				statusHolder.mContent = (TextView)statusView.
						findViewById(R.id.item_homepage_content);
				
				//comment
				statusHolder.mCommentLL=(LinearLayout) statusView
						.findViewById(R.id.item_homepage_comment);
				statusHolder.mCommentTv= (TextView)statusView
						.findViewById(R.id.item_homepage_comment_tv) ;
				//like 
				statusHolder.mLikeLL = (LinearLayout)statusView
						.findViewById(R.id.item_homepage_like);
				statusHolder.mLikeImg= (ImageView)statusView
						.findViewById(R.id.item_homepage_like_img);
				statusHolder.mLikeTv= (TextView)statusView
						.findViewById(R.id.item_homepage_like_tv) ;
				//share
				statusHolder.mShareLL = (LinearLayout)statusView
						.findViewById(R.id.item_homepage_share) ;
				
				statusView.setTag(statusHolder);
			}else {
				statusHolder = (StatusHolder)statusView.getTag() ;
			}
			handleStatusView(status , position, statusHolder);
			convertView = statusView ;
			break;
		case OTHER_TYPE :
			commentView = convertView ;
			Hodler commentHodler  = null ;
			if (commentView == null){
				commentHodler = new Hodler() ;
				commentView = mInflater.inflate(R.layout.item_comment, null) ;
				commentHodler.mAvatar = (CircleImageView)commentView.
						findViewById(R.id.item_comment_avatar) ;
				commentHodler.mUsername = (TextView)commentView.
						findViewById(R.id.item_comment_username) ;
				commentHodler.mTime = (TextView)commentView.
						findViewById(R.id.item_comment_time) ;
				commentHodler.mFloor = (TextView)commentView.
						findViewById(R.id.item_comment_floor) ;
				commentHodler.mContent = (TextView)commentView.
						findViewById(R.id.item_comment_content) ;
				
				commentView.setTag(commentHodler) ;	
			}else {
				commentHodler = (Hodler)commentView.getTag() ;
			}
			
			handleView (getItem(position) , position , commentHodler) ;
			convertView = commentView ;
			break ;

		default:
			break;
		}
		return convertView;
	}
	
	/**
	 * 
	 * @param comment
	 * @param position
	 * @param commentHodler
	 */
	private void handleView(final Comment comment, int position,
			Hodler commentHodler) {
		LogUtils.i(TAG, "comment:"+ comment.getContent()+";"
				+comment.getUser().getUsername()+";") ;
		LogUtils.i(TAG, commentHodler.mUsername == null ?"true": "false") ;
		if (comment.getUser()!= null){
			if (comment.getUser().getUsername()!= null){
				commentHodler.mUsername.setText(comment.getUser().getUsername()+"");
			}
			if (comment.getUser().getPhoto()!= null){
				ImageLoader.getInstance().displayImage(
						comment.getUser().getPhoto().getSmall(),
						commentHodler.mAvatar,
						MyApplication.getInstance().
						getOptions(R.drawable.user_icon_default),
						new SimpleImageLoadingListener()) ;
			}
		}
		// 时间
		commentHodler.mTime.setText(DisplayUtils.transformTime(comment.getTime()));
		//floor 
		commentHodler.mFloor.setText(position+"楼");
		//评论内容
		commentHodler.mContent.setText(comment.getContent()+"");
		//点击头像进入个人中心，这里应该是评论人的个人中心
		commentHodler.mAvatar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent() ;
				Bundle bundle = new Bundle() ;
				bundle.putSerializable("data", comment.getUser()) ;
				intent.putExtras(bundle) ;
				if (comment.getUser().getID().intValue()!= LocalUserUtils.getInstance().
						getLocalUserID().intValue()){
					intent.setClass(mContext, PersonalCenterActivity2.class) ; 
				}else {
					intent.setClass(mContext, PersonalCenterActivity.class) ; //调试
				}
				activity.startActivity(intent);
			}
		}) ;
		
	}

	/**
	 * @param item  //局部的
	 * @param position
	 * @param statusHolder
	 */
	private void handleStatusView(final Status status, int position,
			final StatusHolder statusHolder) {
		if (status!= null && status.getUser()!= null){
			statusHolder.mUsername.setText(status.getUser().getUsername()+""); 
			ImageLoader.getInstance().displayImage(
					status.getUser().getPhoto()!= null ?
							status.getUser().getPhoto().getSmall(): null,
					statusHolder.mAvatar,
					MyApplication.getInstance().
					getOptions(R.drawable.user_icon_default),
					new SimpleImageLoadingListener());
		}
		statusHolder.mTime.setText(DisplayUtils.transformTime(status.getTime())) ;
		if (status.getDistance()!= null){
			statusHolder.mDistance.setText(DisplayUtils.transformDistance(status.getDistance())) ;
		}else {
			statusHolder.mDistance.setVisibility(View.GONE) ;
		}
		//content 显示 
		if (status.getContent()!= null && status.getContent().length()!=0){
			statusHolder.mContent.setVisibility(View.VISIBLE) ;
			statusHolder.mContent.setText(status.getContent()) ;
		}else {
			statusHolder.mContent.setVisibility(View.GONE) ;
		}
		//图片显示 
		final List<Photo> imageList = status.getImageurl() ;
		//建议这里一直写到get(0).getUrl!=null，你的是写到前一个，在有的情况下会出bug 
		if (imageList != null && imageList.size()!=0 && imageList.get(0)!=null &&
				imageList.get(0).getUrl()!= null){
			statusHolder.mImage.setVisibility(View.VISIBLE) ;
			ImageLoader.getInstance().displayImage(
					imageList.get(0).getUrl(), 
					statusHolder.mImage) ;
		}else {
			statusHolder.mImage.setVisibility(View.GONE) ;
		}
		status.setIsLiked(LocalLikeRelationsUtils.getInstance().isLiked(status.getId())) ;
		//是否已经点赞
		if (status.getIsliked()){
			LogUtils.i(TAG, "this is liked");
			statusHolder.mLikeImg.setImageResource(R.drawable.timeline_icon_liked);
		}else {
			statusHolder.mLikeImg.setImageResource(R.drawable.timeline_icon_unlike);
		}
		statusHolder.mLikeTv.setText(status.getUp()+"");//一定要加""
		
		statusHolder.mCommentTv.setText(status.getCommentnum()+"");
		//在评论页面里面，点击图片是查看大图
		statusHolder.mImage.setOnClickListener(new OnClickListener() {	
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent() ;
				Bundle bundle = new Bundle() ;
				bundle.putSerializable("data", status) ;
				intent.putExtras(bundle) ;
				intent.setClass(mContext, GalleryActivity.class) ;
				activity.startActivity(intent);
			}
		}) ;
		//点赞
		statusHolder.mLikeLL.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				doLikeClick(statusHolder, status ) ;
				statusHolder.mLikeImg.startAnimation(scaleAnimation) ;
			}
		}) ;
		//分享
		statusHolder.mShareLL.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String targetUrl = Constant.SHARE_OFFICIAL_URL+"/p.html?id="+status.getId() ;
				String imageUrl = null ;
				if (imageList != null && imageList.size()!=0 && imageList.get(0)!=null
						&& imageList.get(0).getUrl()!= null){
					imageUrl = imageList.get(0).getUrl() ;
				}
				SharePopWindow mShare = new SharePopWindow(mContext,
						status.getContent(),
						Constant.SHARE_TITLE, 
						targetUrl,
						imageUrl, 
						null) ;
				mShare.showAtLocation(activity.getWindow()
						.getDecorView(), Gravity.BOTTOM, 0, 0);
			}
		}) ;
		// 进入个人中心
		statusHolder.mAvatar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent() ;
				Bundle bundle = new Bundle() ;
				bundle.putSerializable("data", status.getUser()) ;
				intent.putExtras(bundle) ;
				if (status.getUser().getID().intValue()!= LocalUserUtils.getInstance()
						.getLocalUserID().intValue()){
					intent.setClass(mContext, PersonalCenterActivity2.class) ;
				}else {
					intent.setClass(mContext, PersonalCenterActivity.class) ;
				}
				activity.startActivity(intent);
			}
		}) ;
		
	}
	
	/**
	 * 都是局部变量.
	 * {status:1,info:'参数错误'/’已经表过态了’}
	 * 看目前 的情况 ，点赞相关的getliked还有问题.很多已经点赞的并没有变色
	 * @param statusHolder
	 * @param status
	 */
	private void doLikeClick(final StatusHolder statusHolder, final Status status){
		//排除已经 点过的情况 ,测试时候点赞后颜色没有变是因为isLiked出了问题
		//有必要重新设计 likerelations.查询得到的完全 是错误的
		if (status.getIsliked()){
			ToastFactory.getToast(mContext,"已经点赞过了").show();
			return ;
		}
		Status tempStatus = new Status(
				LocalUserUtils.getInstance().getLocalUserID(), 
				status.getId()) ;
		String statusJson = new Gson().toJson(tempStatus) ;
		
		httpProxy.doLikeAction(statusJson, new IHttpRequestListener() {
			
			@Override
			public void OnHttpRequestSuccessful(String result, int errCode) {
				LogUtils.i(TAG, "result:"+result) ;
				if (errCode== Constant.ERR_HTTP_REQUEST_SUCCESS){
					ToastFactory.getToast(mContext, "点赞成功").show() ;
					status.increaseUp() ;
					LocalLikeRelationsUtils.getInstance().addLikeRelations(status.getId()) ;
					//立即保存
					LocalLikeRelationsUtils.getInstance().saveLikeRelations();
					LogUtils.i(TAG, "set color for text:"+ status.getUp());
					statusHolder.mLikeImg.setImageResource(R.drawable.timeline_icon_liked);
					statusHolder.mLikeTv.setText(status.getUp()+"") ;//一定要加""
					notifyDataSetChanged() ;
				}else if (errCode == Constant.ERR_HTTP_REQUEST_FAILURE) {
					//参数 错误的中在上面已经排除了
					ToastFactory.getToast(mContext, "点赞失败 result:"+result).show();
				}
			}
			
			@Override
			public void OnHttpRequestStart() {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void OnHttpRequestFailure(String info) {
				ToastFactory.getToast(mContext, "点赞失败").show() ;
			}
		}) ;
		
	}


	private class Hodler {
		public TextView mUsername ;
		public TextView mContent ;
		public TextView mTime ;
		
		public CircleImageView mAvatar ;
		public TextView mFloor ;
	}
	
	private class StatusHolder {
		public CircleImageView mAvatar ;
		private TextView mUsername ;
		
		public TextView mTime ;
		public TextView mDistance ;
		public TextView mContent ;
		public ImageView mImage ;
		
		//like 
		public LinearLayout mLikeLL;
		public TextView mLikeTv;
		public ImageView mLikeImg;
				//share
		public LinearLayout mShareLL;
				//comment
		public LinearLayout mCommentLL;
		public TextView mCommentTv;
		
	}


	

}
